#!/usr/bin/env python
# coding: utf-8
# author: Wesley

import traceback

from django.db import IntegrityError
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from project.settings import BUKA_CONTACT
from apps.student.share import app_logger
from lib.common import AbstractHandler
from lib.push.youmenpush import ios_pusher
from services.datamodel.student.models import mm_Student


class SettingHandler(AbstractHandler):
    def __init__(self):
        AbstractHandler.__init__(self, app_logger)
        self.app_logger = app_logger
        self.METHOD_TAB = {
            'POST': {
                'checkcode': self.handle_checkcode,
                # 'submit': self.handle_submit,
                'modify': self.handle_modify,
                'setavatar': self.handle_chavatar,
                # 'notify_setting': self.handle_notify_setting,
                'setbirth': self.handle_set_birth,
                'setgender': self.handle_set_gender,
            },
            'GET': {
                'pushtest': self.push_test,
                'customer': self.customer
            }
        }

    def push_test(self, request):
        """
        request sample:
        curl http://127.0.0.1:8000/api/parents/setting/?action=pushtest
        """
        payload = {
            "aps":  # 必填 严格按照APNs定义来填写
                {
                    "alert": "亿教测试",  # 必填
                    "badge": 1,  # 可选
                    # "sound": "xx",         # 可选
                    # "content-available":'', # 可选
                    # "category": "xx"      # 可选, 注意: ios8才支持该字段。
                },
            # "key1":"value1",       # 可选 用户自定义内容, "d","p"为友盟保留字段，
            # key不可以是"d","p"
            # "key2":"value2",
        }
        ios_pusher.push_unicast("6b7b42fc16af316449324ac9e22743449aa00cf975ac61316aec724898cec4dd", payload)
        return JsonResponse({'retcode': 1, 'msg': 'ok'})

    @csrf_exempt
    def handle_checkcode(self, request):
        """
        Request sample:
            curl -d 'code=00000000020693098568&pid=3&action=checkcode' -X POST
            http://127.0.0.1:8000/api/parents/setting/

            response like:
                {"school": "\\u4e09\\u5428\\u9ad8\\u4e2d", "retcode": 0, "childname": "\\u502a\\u7855", "cid": 2}
        """
        code = request.param_dict.get('code', None)
        pid = request.param_dict.get('pid', None)
        if not all([code, pid]):
            return JsonResponse({'retcode': 1, 'msg': 'lack of param'})
        child = mm_Student.filter(invitecode=code)
        if child:
            ret, baseinfo = mm_Student.getBasicInfo(child[0].id)
            if ret:
                return JsonResponse({'retcode': 0, 'cid': child[0].id, 'childname': baseinfo['realname'],
                                     'school': baseinfo['schoolname']})
            else:
                return JsonResponse({'retcode': 1, 'msg': baseinfo})
        else:
            return JsonResponse({'retcode': 1, 'msg': '邀请码不存在'})

    def handle_modify(self, request):
        """
        Used to modify realname, phone, 婚姻，教育，地址，职业.
        Post params:
            * action 值固定为modify
            * type 修改类型，取值为name, phone, marriage, edu, address, career
            * value 修改后的值，譬如张三或者138xxxxxxx

        Request sample:
            * change phone
                 curl --cookie "sessionid=b2dpcd3sybkgozeauvunb410y0112bk1" -d 'action=modify&type=phone&value=1234' -X
                 POST http://127.0.0.1:8000/api/student/setting/
            * change name
                curl --cookie "sessionid=b2dpcd3sybkgozeauvunb410y0112bk1" -d 'action=modify&type=name&
                value=%E5%80%AA%E5%8C%A1' -X POST http://127.0.0.1:8000/api/student/setting/
        """
        self.param_in_options(request, "type", ["name", "phone", "marriage", "edu", "address", "career"])
        self.checkMandatoryParams(request, ['type'])
        servicetype = request.param_dict['type']
        if servicetype.strip() != "address":
            self.checkMandatoryParams(request, ["value"])
        else:
            self.checkMandatoryParams(request, ["provinceid", "provincename", "cityid", "cityname", "districtid",
                                                "districtname"])
        value = request.param_dict.get('value', None)
        sid = int(request.session['studentid'])

        try:
            student = mm_Student.get(pk=sid)
        except mm_Student.model.DoesNotExist as e:
            return JsonResponse({'retcode': 1, 'msg': "账号不存在！"})
        if servicetype.strip() == 'name':
            try:
                student.nick_name = value
                # student.user.last_name = value
                # student.user.save()
                student.save()
            except Exception as e:
                app_logger.log(40, e)
                return JsonResponse({'retcode': 1, 'msg': '修改昵称错误！'})
            else:
                return JsonResponse({'retcode': 0})
        elif servicetype.strip() == 'phone':
            try:
                student.mobile = value
                from project.settings import USERNAME_TYPE_PREFIX
                student.user.username = USERNAME_TYPE_PREFIX.STUDENT + value
                student.save()
                student.user.save()
            except IntegrityError as e:
                app_logger.log(40, e)
                return JsonResponse({'retcode': 1, 'msg': "手机号已被使用！"})
            except Exception as e:
                app_logger.log(40, e)
                return JsonResponse({'retcode': 1, 'msg': 'server error'})
            else:
                return JsonResponse({'retcode': 0})
        elif servicetype.strip() == 'marriage':
            student.marriage = int(value)
            student.save()
        elif servicetype.strip() == 'edu':
            student.education = value
            student.save()
        elif servicetype.strip() == 'career':
            student.occupation = value
            student.save()
        elif servicetype.strip() == 'address':
            student.provinceid = request.param_dict["provinceid"]
            student.provincename = request.param_dict["provincename"]
            student.cityid = request.param_dict["cityid"]
            student.cityname = request.param_dict["cityname"]
            student.districtid = request.param_dict["districtid"]
            student.districtname = request.param_dict["districtname"]
            student.save()
        return JsonResponse({'retcode': 0})

    def handle_chavatar(self, request):
        """
        Used to change avadar.
        Params:
            * action  string, 值固定为setvatar
            * url    头像七牛云地址

        curl --cookie "sessionid=b2dpcd3sybkgozeauvunb410y0112bk1" -d 'action=chavatar&url=http://www.baidu.com/p.png'
        -X POST http://127.0.0.1:8000/api/student/setting/
        """
        self.checkMandatoryParams(request, ['url'])

        url = request.param_dict['url']
        try:
            request.user.student.avatar = url
            request.user.student.save()
            return JsonResponse({'retcode': 0})
        except:
            self.app_logger.log(40, traceback.format_exc())
            return JsonResponse({'retcode': 1, 'msg': '更新失败!'})

    def handle_notify_setting(self, request):
        """
        Used to change avadar.
        Params:
            * action  string, 值固定为notify_setting
            * receive_notify 是否接收通知,”1“表示接收，”0”不接收
            * with_sound 通知是否有提示音，”1“表示有声言，”0“没有
            * sound 提示音文件，譬如”default“
            * vibrate 通知是否有振动，”1“表示有振动，”0“没有振动

        curl --cookie "sessionid=b2dpcd3sybkgozeauvunb410y0112bk1" -d 'action=notify_setting&receive_notify=0&with_sound=0&sound=test&vibrate=0' -X POST http://127.0.0.1:8000/api/student/setting/
        """
        for require_param in ['receive_notify', 'with_sound', 'sound', 'vibrate']:
            if require_param not in request.param_dict:
                return JsonResponse(
                    {'retcode': 1,
                     'msg': 'need param`{}`'.format(require_param)})

        receive_notify = request.param_dict['receive_notify']
        with_sound = request.param_dict['with_sound']
        sound = request.param_dict['sound']
        vibrate = request.param_dict['vibrate']
        try:
            student = mm_Student.get(pk=request.session['studentid'])
            student.receive_notify = receive_notify
            student.notify_with_sound = with_sound
            student.notify_sound = sound
            student.notify_shake = vibrate
            student.save()
        except mm_Student.model.DoesNotExist:
            return JsonResponse({'retcode': 1, 'msg': "student does not exist"})
        except Exception as e:
            app_logger.error(e)
            return JsonResponse({'retcode': 1, 'msg': e})
        return JsonResponse({'retcode': 0})

    def handle_set_birth(self, request):
        """
        curl --cookie "sessionid=b2dpcd3sybkgozeauvunb410y0112bk1" -d 'action=setbirth&birth=2016-08-23' -X POST http://127.0.0.1:8000/api/student/setting/
        """
        self.checkMandatoryParams(request, ['birth'])
        try:
            request.user.student.birthday = request.param_dict['birth']
            request.user.student.save()
            return JsonResponse({'retcode': 0})
        except:
            self.app_logger.log(40, traceback.format_exc())
            return JsonResponse({'retcode': 1, 'msg': '更新生日失败!'})

    def handle_set_gender(self, request):
        """
        curl -d 'action=setgender&gender=M' -X POST http://127.0.0.1:8000/api/student/setting/
        """
        self.checkMandatoryParams(request, ['gender'])
        self.param_in_options(request, "gender", ["male", "female", "unknown"])
        try:
            request.user.student.gender = request.param_dict['gender']
            request.user.student.save()
            return JsonResponse({'retcode': 0})
        except:
            self.app_logger.log(40, traceback.format_exc())
            return JsonResponse({'retcode': 1, 'msg': '更新性别失败!'})

    def customer(self, request):
        return self.success(BUKA_CONTACT)


handler = SettingHandler()
